﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using Openfree.Workflow.Common;

public partial class SiteAdmin_WorkflowProcess : BaseUserControl
{
    public EventHandler OnProcessed;
    public EventHandler OnCancel;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="instanceID"></param>
    /// <param name="processVisibled">是否显示审批意见输入内容, 显示审批操作按钮</param>
    /// <returns></returns>
    public bool InitProcess(string instanceID, bool processVisibled, bool showCancelButton)
    {
        if (Request.UrlReferrer.ToString().IndexOf("WorkflowOwner.aspx") > -1 ||
            Request.UrlReferrer.ToString().IndexOf("WorkflowConfirm.aspx") > -1 ||
            Request.UrlReferrer.ToString().IndexOf("WorkflowHistory.aspx") > -1)
        {
            //我的申请事项 页面进入的，不需要是否显示审批意见输入内容, 不需要显示审批操作按钮
            processVisibled = false;
        }
        literalProcess.Text = string.Empty;
        tbDescription.Text = string.Empty;
        
        string cmdText = @"select a.*,
            (select top 1 Username from T_User where UserID= a.UserID) Username,
            (select top 1 Subject from T_SecurityRule where ContainerName = a.ActivityState ) ActivityStateName
            from T_WorkflowProcess a where InstanceID='{0}' order by CreateDate desc";
        DataSet ds = BaseAccess.GetDataSet(base.Connection, string.Format(cmdText, instanceID));

        literalProcess.Text = string.Empty;
        string htmlCode = string.Empty;
        ViewState["ActivityState"] = null;
        foreach (DataRow row in ds.Tables[0].Rows)  
        {
            if (row["UserID"].ToString() == SessionManager.UserID &&
                row["IsProcess"].ToString() == "False")
            {
                ViewState["ActivityState"] = row["ActivityState"].ToString();
                tbDescription.Text = row["Description"].ToString();
            }
            else
            {
                htmlCode = "\t<tr><td style=\"height:30px;\">{0}意见：</td><td style=\"font-size:14px;\">{1}于 {2} {3}了申请<br />{4}</td></tr>\r\n";
                object[] objs = new object[]{row["ActivityStateName"].ToString(),                 
                row["Username"].ToString(),
                DateTime.Parse(row["CreateDate"].ToString()).ToString("yyyy-MM-dd hh:ss"),
                GetProcessStateName(row["ProcessState"].ToString()),
                row["Description"].ToString().Replace("\r", "<br />")};
                literalProcess.Text += string.Format(htmlCode, objs);
            }
        }

        //逻辑有问题，循环里面初始化的ActivityState
        if (ViewState["ActivityState"] != null)
        {
            cmdText = "select Subject from T_SecurityRule where Category='WORKFLOW' and ContainerName='{0}'";
            cmdText = string.Format(cmdText, ViewState["ActivityState"]);
            literalProcessActivity.Text = BaseAccess.ExecuteScalar(base.Connection, cmdText);
        }

        //是否显示审批意见输入内容
        trDescription.Visible = processVisibled;
        btnCancel.Visible = showCancelButton;
        webPanelButtonArea.Visible = showCancelButton;

        hfInstanceID.Value = instanceID;
        hfReadOnly.Value = processVisibled.ToString();
        bool buttonVisible = true;
        if (processVisibled)
        {
            //todo 写死可以优化速度
            ReadOnlyCollection<string> messageList = WorkflowManager.GetEventAllowed(new Guid(instanceID));
            if (messageList.Contains("Update")) btnUpdate.Visible = true;
            if (messageList.Contains("Approve")) btnApprove.Visible = true;
            if (messageList.Contains("SendBack")) btnSendBack.Visible = true;
            if (messageList.Contains("Reject")) btnReject.Visible = true;
        }
        else
        {
            if (ds.Tables[0].Rows.Count == 0)
            {
                //如果列表没有数据，列表不显示，外面区域的按钮需要显示
                pnlView.Visible = false;
                buttonVisible = false;
            }
        }
        return buttonVisible;
    }

    private string GetProcessStateName(string processState)
    {
        string result = string.Empty;
        if ("Approve".Equals(processState))
        {
            result = "<b>同意</b>";
        }
        else if ("SendBack".Equals(processState))
        {
            result = "<b>退回</b>";
        }
        else if ("Reject".Equals(processState))
        {
            result = "<b>拒绝</b>";
        }
        return result;
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        //UpdateProcess();
        //WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
        //workflowService.RaiseUpdateEvent(new Guid(hfInstanceID.Value), null);
        //UpdateProcessActivity();        
    }

    protected void btnApprove_Click(object sender, EventArgs e)
    {
        //工作流向下执行，预先执行主要是为了获得下一节点审批人
        string processActivity = WorkflowManager.GetActivityState(new Guid(hfInstanceID.Value));
        if (ViewState["ActivityState"] != null &&
            processActivity.Equals(ViewState["ActivityState"].ToString()))
        {
            WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
            workflowService.RaiseApproveEvent(new Guid(hfInstanceID.Value), null);
        }
        try
        {
            //todo:最后一个状态执行结束，该工作流获取状态失败
            //RaiseEvent 之后需要有一定延迟，才能获取最新状态
            System.Threading.Thread.Sleep(1000);
            string _processActivity = WorkflowManager.GetActivityState(new Guid(hfInstanceID.Value));
            
            //初始化下一审批人选择名单
            InitGridViewSelect(hfInstanceID.Value, _processActivity);
        }
        catch {
            UpdateWorkflowProcess();

            if (OnProcessed != null) OnProcessed(null, null);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Request["UserID"]))
        {
            base.Alert("请选择一条记录");

            InitGridViewSelect(ViewState["InstanceID"].ToString(), 
                ViewState["ActivityState"].ToString());
            return;
        }
    
        try
        {
            //todo:最后一个状态执行结束，该工作流获取状态失败
            string _processActivity = WorkflowManager.GetActivityState(new Guid(hfInstanceID.Value));
            string cmdText = "update T_Workflow set IsSubmit=1, ProcessActivity ='{0}',ProcessDate='{1}' where InstanceID='{2}'";
            cmdText = string.Format(cmdText, _processActivity, DateTime.Now, hfInstanceID.Value);
            BaseAccess.ExecuteNonQuery(base.Connection, cmdText);

            UpdateWorkflowProcess();
        }
        catch { }

        AddWorkflowProcess(Request["UserID"]);

        if (ViewState["activityID"] != null)
        {
            //从ProcessList页面近来的
            string cmdText = "update T_WorkflowProcess set IsProcess=1 where activityID='{0}'";
            cmdText = string.Format(cmdText, ViewState["activityID"].ToString());
            BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        }

        if (OnProcessed != null) OnProcessed(null, null);
    }


    protected void btnSendBack_Click(object sender, EventArgs e)
    {
        //现在直接退回到草稿状态，工作流这样配置
        WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
        workflowService.RaiseSendBackEvent(new Guid(hfInstanceID.Value), null);


        string cmdText = "select * from T_WorkflowProcess where InstanceID='{0}' and UserID='{1}' and IsProcess=0";
        cmdText = string.Format(cmdText, hfInstanceID.Value, SessionManager.UserID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText, "T_WorkflowProcess");
        DataRow row = ds.Tables[0].Rows[0];
        ViewState["ActivityID"] = row["ActivityID"].ToString();
        row["IsProcess"] = true;
        row["ProcessState"] = "SendBack";
        row["Description"] = tbDescription.Text;
        BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowProcess", ds);

        //现在直接退回到草稿状态，程序写死
        cmdText = "update T_Workflow set IsSubmit=0, ProcessActivity='InitialState' where InstanceID='{0}'";
        cmdText = string.Format(cmdText, hfInstanceID.Value);
        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);

        //todo 将来完善，可以灵活动态选择推给谁
        //System.Threading.Thread.Sleep(1000);
        //string processActivity = WorkflowManager.GetActivityState(new Guid(hfInstanceID.Value));
        //cmdText = "update T_Workflow set ProcessActivity ='{0}',ProcessDate='{1}' where InstanceID='{2}'";
        //cmdText = string.Format(cmdText, processActivity, DateTime.Now, hfInstanceID.Value);
        //BaseAccess.ExecuteNonQuery(base.Connection, cmdText);

        if (OnProcessed != null) OnProcessed(null, null);
    }

    protected void btnReject_Click(object sender, EventArgs e)
    {
        WorkflowService workflowService = (WorkflowService)WorkflowManager.CurrentWorkflowRuntime.GetService(typeof(WorkflowService));
        workflowService.RaiseRejectEvent(new Guid(hfInstanceID.Value), null);

        string cmdText = "select * from T_WorkflowProcess where InstanceID='{0}' and UserID='{1}' and IsProcess=0";
        cmdText = string.Format(cmdText, hfInstanceID.Value, SessionManager.UserID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText, "T_WorkflowProcess");
        DataRow row = ds.Tables[0].Rows[0];
        ViewState["ActivityID"] = row["ActivityID"].ToString();
        row["IsProcess"] = true;
        row["ProcessState"] = "Reject";
        row["Description"] = tbDescription.Text;
        BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowProcess", ds);


        cmdText = "update T_Workflow set ProcessDate='{0}' where InstanceID='{1}'";
        cmdText = string.Format(cmdText, DateTime.Now, hfInstanceID.Value);
        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        if (OnProcessed != null) OnProcessed(null, null);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (OnCancel != null) OnCancel(sender, e);
    }

    public void InitGridViewSelect(string instanceID, string activityState)
    {
        pnlView.Visible = false;
        pnlRole.Visible = true;
        trDescription.Visible = false;
        hfInstanceID.Value = instanceID;

        ViewState["InstanceID"] = instanceID;
        ViewState["ActivityState"] = activityState;
        string cmdText = @"select * from (
	                select a.UserID, a.Username, a.Status, a.IsStat,
	                (select Subject from T_OrgTree where OrgID=b.OrgID and Category='{0}') OrgName,
                    (select QueryCode from T_OrgTree where OrgID=b.OrgID and Category='{0}') QueryCode  
	                from PMS_User a left join T_OrgUser b on a.UserID=b.UserID where OrgID is not null
                )
                m
                right join (
	                select a.Subject RoleSubject, b.UserID from T_SecurityRole a left join T_SecurityPermission b
	                on a.RoleID=b.RoleID where a.Description='{1}'
                )n
                on m.UserID=n.UserID where m.UserID is not null order by m.QueryCode";

        cmdText = string.Format(cmdText, OrgTreeAccess.TREE_XINGZHENG, activityState);

        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
        gridViewSelect.DataSource = ds.Tables[0];
        gridViewSelect.DataBind();
    }

    private void AddWorkflowProcess(string userID)
    {
        DataSet ds = BaseAccess.GetDataSet(base.Connection,
            "select * from T_WorkflowProcess where 1=2", "T_WorkflowProcess");
        DataRow row = ds.Tables[0].NewRow();
        row["ActivityID"] = Guid.NewGuid().ToString();
        row["InstanceID"] = ViewState["InstanceID"].ToString();
        //下一流程审批人
        row["UserID"] = userID;
        row["IsProcess"] = 0;
        row["ActivityState"] = ViewState["ActivityState"].ToString();
        row["CreateDate"] = DateTime.Now.ToString();
        //由下一审批人填写
        row["Description"] = string.Empty;
        ds.Tables[0].Rows.Add(row);
        BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowProcess", ds);
    }

    private void UpdateWorkflowProcess()
    {
        //todo:最后一个状态执行结束，该工作流获取状态失败,IsProcess=0可以判断最后一个
        string cmdText = "select * from T_WorkflowProcess where InstanceID='{0}' and UserID='{1}' and IsProcess=0";
        cmdText = string.Format(cmdText, hfInstanceID.Value, SessionManager.UserID);
        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText, "T_WorkflowProcess");
        if (ds.Tables[0].Rows.Count > 0)
        {
            DataRow row = ds.Tables[0].Rows[0];
            ViewState["ActivityID"] = row["ActivityID"].ToString();
            row["IsProcess"] = true;
            row["ProcessState"] = "Approve";
            row["Description"] = tbDescription.Text;
            BaseAccess.UpdateDataSet(base.Connection, "T_WorkflowProcess", ds);

            cmdText = "update T_Workflow set ProcessDate='{0}' where InstanceID='{1}'";
            cmdText = string.Format(cmdText, DateTime.Now, hfInstanceID.Value);
            BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        }
    }
}
